this repo has no description
at master 60 lines 1.4 kB view raw
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 15package csv 16 17import ( 18 "encoding/csv" 19 "io" 20 "strings" 21 22 "cuelang.org/go/cue" 23) 24 25// Encode encode the given list of lists to CSV. 26func Encode(x cue.Value) (string, error) { 27 var b strings.Builder 28 w := csv.NewWriter(&b) 29 iter, err := x.List() 30 if err != nil { 31 return "", err 32 } 33 for iter.Next() { 34 row, err := iter.Value().List() 35 if err != nil { 36 return "", err 37 } 38 a := []string{} 39 for row.Next() { 40 col := row.Value() 41 if str, err := col.String(); err == nil { 42 a = append(a, str) 43 } else { 44 b, err := col.MarshalJSON() 45 if err != nil { 46 return "", err 47 } 48 a = append(a, string(b)) 49 } 50 } 51 _ = w.Write(a) 52 } 53 w.Flush() 54 return b.String(), nil 55} 56 57// Decode reads in a csv into a list of lists. 58func Decode(r io.Reader) ([][]string, error) { 59 return csv.NewReader(r).ReadAll() 60}