blob: 499df8d0ffa15d0dc955f8c075fcc7e1b5b1265f [file] [log] [blame]
// Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Package starlarkfmt formats Go values as starlark code.
// TODO(kjharland): Use the starlark libraries for this?
package starlarkfmt
import (
"fmt"
"reflect"
"strings"
)
func Format(v reflect.Value) string {
switch v.Kind() {
case reflect.String:
return String(v)
case reflect.Slice:
return Slice(v)
case reflect.Bool:
return Bool(v)
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64,
reflect.Float32, reflect.Float64:
return Num(v)
default:
panic(fmt.Sprintf("unimplemented: %v", v.Kind()))
}
}
func Num(v reflect.Value) string {
return fmt.Sprintf("%d", v.Int())
}
func String(v reflect.Value) string {
return fmt.Sprintf("\"%s\"", v.String())
}
func Slice(v reflect.Value) string {
output := "["
for i := 0; i < v.Len(); i++ {
output += fmt.Sprintf("%s,", Format(v.Index(i)))
}
return output + "]"
}
func Bool(v reflect.Value) string {
return strings.Title(fmt.Sprintf("%t", v.Interface()))
}