github.com/joomcode/cue@v0.4.4-0.20221111115225-539fe3512047/pkg/text/tabwriter/manual.go (about) 1 // Copyright 2018 The CUE Authors 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package tabwriter 16 17 import ( 18 "bytes" 19 "fmt" 20 "text/tabwriter" 21 22 "github.com/joomcode/cue/cue" 23 ) 24 25 // Write formats text in columns. See golang.org/pkg/text/tabwriter for more 26 // info. 27 func Write(data cue.Value) (string, error) { 28 buf := &bytes.Buffer{} 29 tw := tabwriter.NewWriter(buf, 0, 4, 1, ' ', 0) 30 31 write := func(v cue.Value) error { 32 b, err := v.Bytes() 33 if err != nil { 34 return err 35 } 36 _, err = tw.Write(b) 37 if err != nil { 38 return err 39 } 40 return nil 41 } 42 43 switch data.Kind() { 44 case cue.BytesKind, cue.StringKind: 45 if err := write(data); err != nil { 46 return "", err 47 } 48 case cue.ListKind: 49 for i, _ := data.List(); i.Next(); { 50 if err := write(i.Value()); err != nil { 51 return "", err 52 } 53 _, _ = tw.Write([]byte{'\n'}) 54 } 55 default: 56 return "", fmt.Errorf("tabwriter.Write: unsupported type %v", data.Kind()) 57 } 58 59 err := tw.Flush() 60 return buf.String(), err 61 }