github.com/scottwinkler/terraform@v0.11.6-0.20180329211809-05143987aea8/repl/format.go (about)

     1  package repl
     2  
     3  import (
     4  	"bufio"
     5  	"bytes"
     6  	"fmt"
     7  	"sort"
     8  	"strings"
     9  )
    10  
    11  // FormatResult formats the given result value for human-readable output.
    12  //
    13  // The value must currently be a string, list, map, and any nested values
    14  // with those same types.
    15  func FormatResult(value interface{}) (string, error) {
    16  	return formatResult(value)
    17  }
    18  
    19  func formatResult(value interface{}) (string, error) {
    20  	switch output := value.(type) {
    21  	case string:
    22  		return output, nil
    23  	case []interface{}:
    24  		return formatListResult(output)
    25  	case map[string]interface{}:
    26  		return formatMapResult(output)
    27  	default:
    28  		return "", fmt.Errorf("unknown value type: %T", value)
    29  	}
    30  }
    31  
    32  func formatListResult(value []interface{}) (string, error) {
    33  	var outputBuf bytes.Buffer
    34  	outputBuf.WriteString("[")
    35  	if len(value) > 0 {
    36  		outputBuf.WriteString("\n")
    37  	}
    38  
    39  	lastIdx := len(value) - 1
    40  	for i, v := range value {
    41  		raw, err := formatResult(v)
    42  		if err != nil {
    43  			return "", err
    44  		}
    45  
    46  		outputBuf.WriteString(indent(raw))
    47  		if lastIdx != i {
    48  			outputBuf.WriteString(",")
    49  		}
    50  		outputBuf.WriteString("\n")
    51  	}
    52  
    53  	outputBuf.WriteString("]")
    54  	return outputBuf.String(), nil
    55  }
    56  
    57  func formatMapResult(value map[string]interface{}) (string, error) {
    58  	ks := make([]string, 0, len(value))
    59  	for k, _ := range value {
    60  		ks = append(ks, k)
    61  	}
    62  	sort.Strings(ks)
    63  
    64  	var outputBuf bytes.Buffer
    65  	outputBuf.WriteString("{")
    66  	if len(value) > 0 {
    67  		outputBuf.WriteString("\n")
    68  	}
    69  
    70  	for _, k := range ks {
    71  		v := value[k]
    72  		raw, err := formatResult(v)
    73  		if err != nil {
    74  			return "", err
    75  		}
    76  
    77  		outputBuf.WriteString(indent(fmt.Sprintf("%s = %v\n", k, raw)))
    78  	}
    79  
    80  	outputBuf.WriteString("}")
    81  	return outputBuf.String(), nil
    82  }
    83  
    84  func indent(value string) string {
    85  	var outputBuf bytes.Buffer
    86  	s := bufio.NewScanner(strings.NewReader(value))
    87  	for s.Scan() {
    88  		outputBuf.WriteString("  " + s.Text())
    89  	}
    90  
    91  	return outputBuf.String()
    92  }